/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package op;

import core.CreateConta;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Jônatas
 */
public class CreateContaPabxVicol implements CreateConta {

    public static Pattern patternValor = Pattern.compile("[0-9]*[,][0-9]{2}");
    public static Pattern patternLigacao = Pattern.compile("[0-9]{2}/[0-9]{2}/[0-9]{2} "
            + "[0-9]{2}:[0-9]{2}:[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}");

    public ContaTelefonica createConta(String[] fullFile) throws Exception {

        Telefone origem = null;

        ContaTelefonica contaTelefonica = new ContaTelefonica();

        contaTelefonica.contaMensal = new ArrayList<EntradaAbstrata>();

        for (String line : fullFile) {

            line = line.trim();

            if (line.isEmpty()) {
                continue;
            }

            if (line.toLowerCase().startsWith("ramal")) {
                StringTokenizer tokenizer = new StringTokenizer(line);
                tokenizer.nextToken();

                String numRamal = tokenizer.nextToken();

                int index = line.indexOf("rio");

                String subLine = line.substring(index + "rio".length());

                origem = new Telefone(numRamal + " - " + subLine.trim(), true);

                continue;
            }

            if (origem == null) {
                continue;
            }

            if (line.startsWith("Total")) {
                continue;
            }

            Matcher matchLigacao = patternLigacao.matcher(line);

            if (!matchLigacao.find()) {
                continue;
            }

            // Eh ligacao

            Matcher matchValor = patternValor.matcher(line);

            String valor = "";

            boolean temValor = matchValor.find();

            if (!temValor) {
                valor = "0,00";
            } else {
                valor = matchValor.group();
            }

            

            Map<String, Object> parametersMap = new HashMap<String, Object>();
            parametersMap.put("line", line);
            parametersMap.put("valor", valor);
            parametersMap.put("origem", origem);
            parametersMap.put("temValor", new Boolean(temValor));

            EntradaAbstrata entrada = new QuebraStringPabxVicol().quebraString(parametersMap);

            contaTelefonica.contaMensal.add(entrada);
        }


        Collections.sort(contaTelefonica.contaMensal, new ComparatorEntradaAbstrataPorTelefone());

        contaTelefonica.contaResumida();

        return contaTelefonica;

    }
}
